package top.infopub.mgr.bpa.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.bpa.OtherContractsReviewDto;
import top.infopub.enums.bpa.CostTypesEnum;
import top.infopub.enums.bpa.SettlementPatternEnum;
import top.infopub.enums.mkt.BackMechEnum;
import top.infopub.enums.mkt.ProjectFormatEnum;
import top.infopub.mgr.bpa.domain.OtherConLedgerDomain;
import top.infopub.mgr.bpa.domain.OtherConReviewDomain;
import top.infopub.mgr.bpa.service.OtherContractsReviewService;
import top.infopub.mgr.bpa.vo.ContractManageVo;
import top.infopub.mgr.bpa.vo.OtherConReviewVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.mkt.service.MarketManageService;
import top.infopub.model.bpa.Basic;
import top.infopub.model.bpa.OtherContractsReview;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 其他合同评审 前端控制器
 * </p>
 *
 * @author wangkai
 * @since 2021-06-15
 */
@Controller
@RequestMapping("/contractsReview")
public class OtherContractsReviewController  extends GenericFlowController {
    @Autowired
    OtherContractsReviewService otherContractsReviewService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private MarketManageService marketManageService;

    /**
     * 跳转
     *
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        //获取登录人员信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        //查询区域公司列表
        List<OrgInfo> orgInfoList = marketManageService.queryOrgInfoByAuthUserId(vo);
        request.setAttribute("orgInfoList", orgInfoList);
        //查询营销人员列表
        List<StaffInfo> staffInfoList = marketManageService.queryStaffInfoByAuthUserId(vo);
        request.setAttribute("staffInfoList", staffInfoList);
        return "bpa/lay-otherConReview-list";
    }


    /**
     * 其他合同评审列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<OtherConReviewDomain> queryDataByCondition(OtherConReviewVo otherConReviewVo,
                                                            ParamPage paramPage) throws ParseException {
        Page<OtherConReviewDomain> page = new Page<OtherConReviewDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (otherConReviewVo.getEndDate() != null) {
            otherConReviewVo.setEndDate(DateUtils.addDays(otherConReviewVo.getEndDate(), 1));
        }
        page = otherContractsReviewService.selectByDomainWhere(page, otherConReviewVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 其他合同台账
     *
     * @return
     */
    @RequestMapping("/selectByLedger")
    @ResponseBody
    public RspVo<OtherConLedgerDomain> selectByLedger(ContractManageVo contractManageVo, ParamPage paramPage) throws ParseException {
        Page<OtherConLedgerDomain> page = new Page<OtherConLedgerDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (contractManageVo.getEndDate() != null) {
            contractManageVo.setEndDate(top.infopub.mgr.util.DateUtils.addDays(contractManageVo.getEndDate(), 1));
        }
        page = otherContractsReviewService.selectByLedger(page, contractManageVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    //下拉框数据
    @RequestMapping("/projectDropDownBox")
    @ResponseBody
    public List<Map<String,String>> projectDropDownBox() {
        return otherContractsReviewService.projectDropDownBox();
    }



    /*公司名称下拉框*/
    @RequestMapping("/companyNameDropDownBox")
    @ResponseBody
    public List<Map<String,String>> companyNameDropDownBox(String types) {
        return otherContractsReviewService.companyNameDropDownBox(types);
    }

    //详情
    @RequestMapping("/queryById")
    @ResponseBody
    public OtherContractsReviewDto queryById(String id) {
        OtherContractsReviewDto dao =  otherContractsReviewService.queryById(id);
        return dao;
    }
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id) {
        request.setAttribute("id",id);
        return "bpa/lay-OtherContractReview-detail";
    }


    //下拉详情
    @RequestMapping("/projectBasic")
    @ResponseBody
    public Basic projectBasic(String proCode) {
        Basic basic =  otherContractsReviewService.projectBasic(proCode);
        return basic;
    }

    /*页面费用类型下拉框*/
    @RequestMapping("/costTypesEnum")
    @ResponseBody
    public List<Map<String, String>> costTypesEnum() {
        return  CostTypesEnum.asList();
    }

    /*回报机制*/
    @RequestMapping("/rewardSystem")
    @ResponseBody
    public List<Map<String, String>>  rewardSystem() {
        return BackMechEnum.asList();
    }

    /*项目业态*/
    @RequestMapping("/projectForms")
    @ResponseBody
    public List<Map<String, String>>  projectForms() {
        return ProjectFormatEnum.asList();
    }



    /*页面合同结算方式下拉框*/
    @RequestMapping("/settlementPatternEnum")
    @ResponseBody
    public List<Map<String, String>> settlementPatternEnum() {
        return  SettlementPatternEnum.asList();
    }

    // 保存提交
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String bodyStr, String submitType, String proCode,String id) {
        if (StringUtils.isEmpty(bodyStr)) {
            return RspVo.getFailureResponse(0, "数据为空");
        }
        //登录人员信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String object = StringEscapeUtils.unescapeJava(bodyStr);
        OtherContractsReviewDto dto = JSON.parseObject(object, OtherContractsReviewDto.class);

        /**
         * 附件处理
         * */
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(dto.getFileAtt()!=null){
            String[] fileAtt = dto.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo,proCode,file);
                attachmentList.add(attachment);
            }
        }

        if ("0".equals(submitType)) {//0是保存
            int i = otherContractsReviewService.save(dto,attachmentList);
            if (i > 0) {
                return RspVo.getSuccessResponse(0, "保存成功");
            } else {
                return RspVo.getFailureResponse(0, "保存失败");
            }
        } else { //1是提交
            //判断状态
            OtherContractsReview  contractsReview  = otherContractsReviewService.findById(id);
            if (contractsReview!=null)
            {
                String processStatus = contractsReview.getProcessStatus();
                if ("1".equals(processStatus) || "9".equals(processStatus))
                {
                    return RspVo.getFailureResponse(0, "审批中或审批已完成，修改失败");
                }
            }

            if (StringUtils.isNotBlank(contractsReview.getOaId())) {
                oaFlowService.finishOA(contractsReview.getOaId());
            }
            //提交流程  先保存
            int i = otherContractsReviewService.save(dto,attachmentList);
            if (i > 0) {//保存成的情况 走流程
                //发起流程
                /*String process = proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE15, object, id, code, vo);*/
                /*保存对内合同金额合计*/

                return RspVo.getFailureResponse(0, "提交成功");
            } else { //提交-保存失败
                return RspVo.getFailureResponse(0, "提交失败");
            }
        }
    }

    //删除子项目表数据
    @RequestMapping("/deleteGenerationPay")
    public void deleteGenerationPay(String id) {
        otherContractsReviewService.deleteGenerationPay(id);
    }
}
